package com.yourenbang.lingyun.transaction.util.taishuikang;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author .
 * @date 2021/3/30.
 * @time 18:13.
 */
public class SignUtil {

    public static final String RM = "sign";
    public static final String APP_SECRET = "appSecret";

    public static void main(String[] args) {
//        //加签举例
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("grantGUID", "8aeb95678c054d9096151ae0fe4e8164");
//        //paramMap.put("cooperationID", "6b81017d19f04535aa56a5721a48287b");
        paramMap.put("merchantId", "7265b2b37bc74c4bbd4048265c8a90b8");
////        paramMap.put("customRate", "0");
////        paramMap.put("personalRate", "0");
////        paramMap.put("orderFormUrl", "https://api.taishuikang.com/upload/c6df32ed587a408cac1813f196df5820.xls");
////        paramMap.put("serviceRateType", "MERCHANTBEAR");
//       // paramMap.put("rejectExplain", "");
//        //paramMap.put("auditStatus", "ADOPT");
//        //paramMap.put("orderTradeNo", "N202103291734010002");
        long l = System.currentTimeMillis();
        paramMap.put("timestamp", l + "");
        System.out.println(l+"");
        String sign = SignUtil.getSign(JSON.parseObject(JSON.toJSONString(paramMap)), "afeb523441a170f8");
        System.out.println(sign);

        Map<String,Object> maps = (Map)JSON.parse("{\"buyer_fee\":\"0.00\",\"charset\":\"UTF-8\",\"fail_code\":\"F9999\",\"fail_reason\":\"对方账号不存在\",\"inner_trade_no\":\"101162056322198365722\",\"is_success\":\"T\",\"outer_inst_order_no\":\"SN202105090000006486T\",\"outer_trade_no\":\"SN202105090000006486T\",\"product_code\":\"10210\",\"seller_fee\":\"0.00\",\"trade_amount\":\"34585.00\",\"trade_status\":\"TRADE_FAILED\",\"trade_time\":\"20210509202953\"}");


        String error_msg = maps.get("error_msg").toString();
        if(StringUtils.isBlank(error_msg)){
            error_msg = maps.get("fail_reason").toString();
        }

        System.out.println(error_msg);

//       String file2 = "2021040910130010112146080011780054951959+N202104092045210001T.pdf";
//        String orderTradeNo = file2.substring(file2.lastIndexOf("+") + 1, file2.length() - 5);
//        System.out.println("SN202104130000000023T".substring(0, "SN202104130000000023T".length() - 1));
    }

    /**
     * 获取签名
     *
     * @param paramMap  包含所有业务参数，和appKey,nonce,timestamp这3个公共参数
     * @param appSecret
     * @return
     */
    public static String getSign(Map<String, Object> paramMap, String appSecret) {
        String text = getUrlText(paramMap);
        text += "&appSecret=" + appSecret;
        return DigestUtils.md5DigestAsHex(text.getBytes()).toUpperCase();
    }
    private static String getUrlText(Map<String, Object> beanMap) {
        beanMap = getSortedMap(beanMap);
        StringBuilder builder = new StringBuilder();
        for (String key : beanMap.keySet()) {
            String value = beanMap.get(key).toString();
            builder.append(key);
            builder.append('=');
            builder.append(value);
            builder.append('&');
        }
        String text = builder.toString();
        return text.substring(0, text.length() - 1);
    }
    public static Map<String, String> transMap(String str) {
        String[] key_value = str.split("&");
        Map<String, String> map = new HashMap<String, String>();
        for (String e : key_value) {
            String[] value = e.split("=");
            if(value == null || value.length != 2){
                continue;
            }
            map.put(value[0], value[1]);
        }
        return map;
    }
    /**
     * 对普通map进行排序
     *
     * @param paramMap
     * @return
     */
    private static Map<String, Object> getSortedMap(Map<String, Object> paramMap) {
        SortedMap<String, Object> map = new TreeMap<String, Object>();
        for (String key : paramMap.keySet()) {
            if (key != null && !APP_SECRET.equals(key) && !RM.equals(key)) {
                Object value = paramMap.get(key);
                if (value != null) {
                    String valueStr = String.valueOf(value);
                    if (valueStr != null && !"".equals(valueStr)) {
                        map.put(key, value);
                    }
                }
            }
        }
        return map;
    }
    public static String getUrlParams(Map<String, Object> beanMap) {
        StringBuilder builder = new StringBuilder();
        for (String key : beanMap.keySet()) {
            String value = "";
            if(beanMap.get(key) != null ){
                value = beanMap.get(key).toString();
            }
            builder.append(key);
            builder.append('=');
            builder.append(value);
            builder.append('&');
        }
        String text = builder.toString();
        return text.substring(0, text.length() - 1);
    }
}
